package com.blb.io;

import java.io.*;

public class FileIODemo {

    /**
     * 字节流读取文件
     * @param path
     */
    public static void read(String path){
        //创建文件输入流
        try(FileInputStream in = new FileInputStream(path)) {
            //字节数组接收数组
            byte[] buffer = new byte[100];
            //读取长度
            int len = 0;
            //循环从文件流中读取到字节数组中
            while((len = in.read(buffer)) != -1){
                //把字节数组转换为字符串
                String s = new String(buffer, 0, len, "utf-8");
                System.out.print(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 字节流写入文字
     * @param path
     * @param content
     */
    public static void write(String path,String content){
        //创建文件输出流
        try(FileOutputStream out = new FileOutputStream(path)){
            //将字符串转换为字节数组
            byte[] bytes = content.getBytes("utf-8");
            //写入数据
            out.write(bytes);
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }

    /**
     * 文件复制
     * @param source
     * @param target
     */
    public static void copy(String source,String target){
        try(FileInputStream in = new FileInputStream(source);
            FileOutputStream out = new FileOutputStream(target)){
            byte[] buffer = new byte[100];
            int len = 0;
            while((len = in.read(buffer)) != -1){
                out.write(buffer,0,len);
            }
            System.out.println("复制完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 带缓冲的文件复制
     * @param source
     * @param target
     */
    public static void copyBuffered(String source,String target){
        try(BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target))){
            byte[] buffer = new byte[100];
            int len = 0;
            while((len = in.read(buffer)) != -1){
                out.write(buffer,0,len);
            }
            System.out.println("复制完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
//        read("C:\\Users\\Administrator\\Desktop\\面试题3.md");
//        write("C:\\Users\\Administrator\\Desktop\\xx.txt","Hello我们学习IO了");
        long start = System.currentTimeMillis();
        copy("D:\\install\\otp_win64_22.0.exe","D:\\xx.exe");
        long end = System.currentTimeMillis();
        System.out.println("复制耗时：" +(end - start));
        start = System.currentTimeMillis();
        copyBuffered("D:\\install\\otp_win64_22.0.exe","D:\\xx1.exe");
        end = System.currentTimeMillis();
        System.out.println("复制耗时：" +(end - start));
    }
}
